<template>
  <div class="page_index">
    <!-- 顶部 -->
    <div class="page_top">
      <div class="btn_activity_desc">活动攻略</div>
      <img class="page_top_bg"
           src="@/assets/img/index_header.png"
           alt="七夕背景"
           srcset="">

      <div @click="handleJoinActive"
           v-if="config.activityType === 0 "
           class="btn_activity_join">立即参与</div>
      <div v-else
           class="activity_close_box flex justify-between  ">
        <div class="btn_my_love">
          <router-link to="/myLovePage"
                       tag="span">我的爱情主页</router-link>
        </div>
        <div class="btn_award_list">
          <router-link tag="span"
                       to="/winnersList">获奖名单</router-link>
        </div>
      </div>
    </div>

    <div v-if="monyReward.length"
         class="page_content">
      <Reward :monyReward="monyReward"
              :kindReward="kindReward"
              @handleGoToPrizeList="handleGoToPrizeList"></Reward>

      <!-- 列表 -->
      <div class="container">
        <div class="sticky">
          <div class="search-box flex align-center">
            <img src="@/assets/img/search.png"
                 class="search-icon"
                 alt="搜索">
            <input type="text"
                   class="search-ipt"
                   placeholder="搜索好友ID或者昵称，祝福他们">
          </div>

          <div class="tab-list flex ">
            <div v-for="(item,index) in tabList"
                 :key="index"
                 class="tab flex-1"
                 :class="{select:index==tabIdx}"
                 @click="handleTabChange(index)">{{item}}</div>
          </div>
        </div>

        <div class="list flex justify-between flex-warp">
          <div v-for="(lists, index) in userList"
               :key="index">
            <div class="item"
                 v-for="(item,idx) in lists"
                 :key="idx">
              <div class="img-box">
                <span v-show="tabIdx > 0"
                      class="ranking">{{item.ranking}}</span>
                <img class="img"
                     :src="item.img" />
              </div>
              <div class="user-item-bottom">
                <div class="num-box flex justify-between align-center">
                  <span class="id">ID:{{item.id}}</span>
                  <div class="flex  align-center">
                    <span class="num">{{item.num}}</span>
                    <span>票</span>
                  </div>
                </div>
                <div class="name">{{item.gril}}&{{item.boy}}</div>
                <div @click="handleShowVote(item.id,index,idx)"
                     class="btn">{{ !config.loginType || config.votesNum? '祝福他们':'已祝福'}}</div>
              </div>

            </div>
          </div>
        </div>
        <div v-show="isLodingMoreData"
             class="in_loading flex align-center justify-center ">
          <img src="@/assets/img/loading.gif">
          <span>努力加载中...</span>
        </div>
        <p v-show="offset>=maxOffset"
           class="no-more">没有更多了</p>
      </div>

    </div>

    <Blessing :blessing="blessing"
              :showBlessingDialog="showBlessingDialog"
              @changeBlessing="changeBlessing"
              @vote="handleVote"
              @close="showBlessingDialog=false"
              @input="handleBlessingInput"></Blessing>

    <MoreVotes @close="showMoreVotesDialog = false"
               :showMoreVotesDialog="showMoreVotesDialog"></MoreVotes>

  </div>
</template>

<script>
import { getScrollHeight, getScrollTop, getWindowHeight } from "@/utils/utils";
import MoreVotes from "@/components/moreVotes/moreVotes"
import Blessing from "@/components/blessing/blessing"
import Reward from "./modules/reward/reward"
export default {
  components: {
    MoreVotes,
    Blessing,
    Reward
  },
  data() {
    return {
      config: {
        loginType: true,
        activityType: 0, // 0 进行中 1 已结束
        votesNum: 1, // 剩余票数
        userId: 111111, // 个人用户id
      },
      // 现金奖励
      monyReward: [],
      // 冲榜奖励
      kindReward: [],
      // 用户列表 
      originList: [],
      userList: [[], []],
      offset: 1,
      maxOffset: 3,
      limit: 20, // 20
      tabList: ['最新上传', '总榜单', '我祝福过'],
      tabIdx: 1, // 0 最新上传 1 总榜单 2 我祝福过

      blessing: '',
      blessingList: [],
      showBlessingDialog: false,
      blessingDialogConfig: {
        type: 0,
        idx: 0
      },
      showMoreVotesDialog: false,
      isLodingMoreData: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        window.addEventListener('scroll', this.debounce(this.load));
      }, 800);
    })
  },
  destroyed() {
    window.removeEventListener('scroll', this.debounce(this.load), false);
  },
  created() {
    this.getRewardList()
    this.getBlessingList()
    this.getList()
  },
  methods: {
    handleMoreVotesDialogClose() {
      this.showMoreVotesDialog = false
    },
    handleJoinActive() {
      if (!this.config.loginType) {
        this.$toast('请先登录!')
        return
      }
      this.$router.push('/uploadMyLove')
    },
    handleGoToPrizeList() {
      if (!this.config.loginType) {
        this.$toast('请先登录!')
        return
      }
      this.$router.push('/prizeList')
    },
    getRewardList() {
      this.$api.apiHomeRewardList().then(res => {
        console.log('奖品列表', res);
        this.monyReward = res.data.monyReward
        this.kindReward = res.data.kindReward
      })
    },
    getBlessingList() {
      this.$api.apiHomeBlessing().then(res => {
        console.log('祝福语列表', res);
        this.blessingList = res.data.text
        this.changeBlessing()
      })
    },
    handleShowVote(id, type, idx) {
      if (!this.config.loginType) {
        this.$toast('请先登录!')
      } else if (this.config.votesNum <= 0) {
        // this.$toast('今日票数已用完!')
        this.showMoreVotesDialog = true
      } else {
        this.blessingDialogConfig.type = type
        this.blessingDialogConfig.idx = idx
        this.showBlessingDialog = true
      }
    },
    handleBlessingInput(e) {
      this.blessing = e
    },
    handleVote() {
      if (!this.blessing) {
        this.$toast('请输入祝福语!')
        return
      }
      this.showBlessingDialog = false
      this.userList[this.blessingDialogConfig.type][this.blessingDialogConfig.idx].num++
      this.calcList()
      this.config.votesNum--
      console.log(this.config.votesNum);
    },
    debounce(fn, time = 300) {
      let timer = null
      return function () {
        if (timer) clearTimeout(timer)
        timer = setTimeout(fn, time);
      }
    },
    load() {
      if (getScrollTop() + getWindowHeight() >= getScrollHeight()) {
        if (this.offset < this.maxOffset) {      //先判断下一页是否有数据  
          console.log('下一页');
          this.getList();              //拉取接口数据
        } else {
          //到底了
        }
      }
    },

    handleTabChange(tabIdx) {
      if (!this.config.loginType) {
        this.$toast('请先登录!')
        return
      }
      this.tabIdx = tabIdx
      this.offset = 1
      this.calcList()
    },
    getIntRandom(lowerValue, upperValue) {
      return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
    },
    async getList() {
      // this.$toast.loading({
      //   message: '加载中...',
      //   duration: 800,
      //   forbidClick: true,
      // });
      if (this.isLodingMoreData) return;
      this.isLodingMoreData = true
      this.$api.apiHomeUsers().then(res => {
        console.log('用户列表', res);
        this.originList = this.originList.concat(res.data.list)
        this.calcList()
        this.isLodingMoreData = false
      })
    },
    loadImagesHeight(list) {
      var count = 0; //用来计数，表示是否所有图片高度已经获取
      list.forEach((item, index) => {
        //创建图片对象，加载图片，计算图片高度
        var img = new Image();
        img.src = item.img;
        img.onload = () => {
          count++;

          // list[index].imgHeight = img.height;
          list[index].imgHeight = Math.round(img.height * 325 / img.width);

          //加载完成最后一个图片高度，开始下一步数据处理
          if (count == list.length) {
            let bottom = 80
            let lHeight = 0
            let rHeight = 0
            let lArr = [];
            let rArr = [];
            for (var i = 0; i < list.length; i++) {
              if (rHeight + (rArr.length * bottom) < lHeight + (lArr.length * bottom)) {
                // console.log(`第${i + 1}个在右边，左侧高度${lHeight}，右侧高度${rHeight}->${rHeight + list[i].imgHeight + 100}`)
                rHeight += (list[i].imgHeight + bottom)
                rArr.push(list[i]);
              } else if (rHeight + (rArr.length * bottom) > lHeight + (lArr.length * bottom)) {
                // console.log(`第${i + 1}个在左边，左侧高度${lHeight}->${lHeight + list[i].imgHeight + 100}，右侧高度${rHeight}`)
                lHeight += (list[i].imgHeight + bottom)
                lArr.push(list[i]);
              } else if (rHeight + (rArr.length * bottom) == lHeight + (lArr.length * bottom)) {
                // console.log(`第${i + 1}个在左边，左侧高度${lHeight}->${lHeight + list[i].imgHeight + 100}，右侧高度${rHeight}`)
                lHeight += (list[i].imgHeight + bottom)
                lArr.push(list[i]);
              }
            }
            this.userList = [lArr, rArr]
          }
        }
      })
    },
    calcList() {
      let originList = this.originList.slice(0)
      if (this.tabIdx == 0) {
        originList.sort((a, b) => {
          return b.createTime - a.createTime
        })

      } else if (this.tabIdx == 1) {
        originList.sort((a, b) => {
          return b.num - a.num
        }).map((i, idx) => {
          i.ranking = idx + 1
        })

      } else if (this.tabIdx == 2) {
        originList.sort((a, b) => {
          return b.num - a.num
        }).map((i, idx) => {
          i.ranking = idx + 1
        }).sort((a, b) => {
          return b.voteTime - a.voteTime
        })
        originList = originList.filter(i => {
          return (i.voteList.indexOf(this.config.userId) > -1)
        })
      }

      this.offset++

      // let lArr = [];
      // let rArr = [];
      // for (var i = 0; i < originList.length; i++) {
      //   if (i % 2 == 0) {
      //     lArr.push(originList[i]);
      //   } else {
      //     rArr.push(originList[i]);
      //   }
      //   this.userList = [lArr, rArr]
      // }


      this.loadImagesHeight(originList)

    },
    changeBlessing() {
      this.blessing = this.blessingList[this.getIntRandom(0, this.blessingList.length - 1)]
    }
  }
}
</script>

<style lang='scss'  >
@import "./css/index.scss";
</style>